package com.lj.luoye.lotteryticket;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.lj.luoye.lotteryticket.analysis.AnalyzeCallback;
import com.lj.luoye.lotteryticket.analysis.CheckCallback;
import com.lj.luoye.lotteryticket.analysis.UnionlottoAnalyzer;
import com.lj.luoye.lotteryticket.analysis.UnionlottoFromStoreAndNetAnalyzer;
import com.lj.luoye.lotteryticket.analysis.WinningAnalyzer;
import com.lj.luoye.lotteryticket.dao.LotteryBuyDao;
import com.lj.luoye.lotteryticket.dao.LotteryBuyMultiDao;
import com.lj.luoye.lotteryticket.dao.LotteryHistoryDao;
import com.lj.luoye.lotteryticket.dialog.CommonDialog;
import com.lj.luoye.lotteryticket.dialog.MyDialogUtil;
import com.lj.luoye.lotteryticket.entity.LuckEntity;
import com.lj.luoye.lotteryticket.entity.Unionlotto;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView foretellTv;

    private Button generateBt1;
    private Button generateBt2;
    private Button generateBt5;
    private Button generateBt10;
    private Button generateBt15;
    private Button generateBt20;
    private Button generateBt50;
    private Button generateBt100;

    private Button generateMultiBt1;
    private Button generateMultiBt2;
    private Button generateMultiBt8;
    private Button generateMultiBt16;

    private Button buyBt;
    private Button checkBt;
    private TextView latestRightTv;
    private TextView luckResultTv;
    private Spinner lotteryDateSp;
    private Button statisticBt;
    private Button exportBt;
    private Button importBt;
    private ArrayAdapter<String> adapter;

    private LotteryBuyDao lotteryBuyDao;
    private LotteryBuyMultiDao lotteryBuyMultiDao;
    private LotteryHistoryDao lotteryHistoryDao;
    private UnionlottoAnalyzer unionlottoAnalyzer;
    private Handler generateHandler;

    private String selectedDate;
    private List<String> dates=new ArrayList<>();
    private WinningAnalyzer winningAnalyzer;
    private Handler checkHandler;

    private KProgressHUD hud;


    private Button cleanBt;
    private EditText hrefTv;

    private void generateUnionlottos(final String date, final int count, final boolean multi){
        hud.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                unionlottoAnalyzer.analyze(new AnalyzeCallback() {
                    @Override
                    public void callBack(Result result) {
                        if(result.ok){
                            List<Unionlotto> currentUnionlottoList=lotteryBuyDao.getByDate(date);
                            if(currentUnionlottoList.size()>0){
                                String str="";
                                int i=1;
                                for(Unionlotto unionlotto:currentUnionlottoList){
                                    str+=i+"、";
                                    str+=unionlotto.description+": ";
                                    for(String redBall:unionlotto.redBalls){
                                        str+=redBall+" ";
                                    }
                                    str+="- "+unionlotto.blueBall+"\n";
                                    i++;
                                }
                                Message msg=new Message();
                                Bundle bundle=new Bundle();
                                bundle.putBoolean("ok",result.ok);
                                bundle.putString("us",str);
                                msg.setData(bundle);
                                generateHandler.sendMessage(msg);
                            }else {//复选
                                List<Unionlotto> currentUnionlottoListMulti=lotteryBuyMultiDao.getByDate(date);
                                if(currentUnionlottoListMulti.size()>0){
                                    String str="";
                                    int i=1;
                                    for(Unionlotto unionlotto:currentUnionlottoListMulti){
                                        str+=i+"、";
                                        str+=unionlotto.description+": ";
                                        for(String redBall:unionlotto.redBalls){
                                            str+=redBall+" ";
                                        }
                                        str+="- ";
                                        for(String blueBall:unionlotto.blueBalls){
                                            str+=blueBall+" ";
                                        }
                                        str+="(复选)\n";
                                        i++;
                                    }
                                    Message msg=new Message();
                                    Bundle bundle=new Bundle();
                                    bundle.putBoolean("ok",result.ok);
                                    bundle.putString("us",str);
                                    msg.setData(bundle);
                                    generateHandler.sendMessage(msg);
                                }
                            }
                        }else{
                            Message msg=new Message();
                            Bundle bundle=new Bundle();
                            bundle.putBoolean("ok",result.ok);
                            bundle.putString("msg",result.msg);
                            msg.setData(bundle);
                            generateHandler.sendMessage(msg);
                        }
                        hud.dismiss();
                    }
                },count,multi);
            }
        }).start();
    }

    private LuckEntity getLuckEntity(List<LuckEntity> luckEntityList,int id){
        for(LuckEntity l:luckEntityList){
            if(l.unionlotto.id==id){
                return l;
            }
        }
        return null;
    }

    private String printRight(Unionlotto unionlotto, LuckEntity luckEntity){
        String str="";
        str+=unionlotto.description+"：";
        for(String redBall:unionlotto.redBalls){
            boolean has=false;
            for(String r:luckEntity.unionlotto.redBalls){
                if(r.equals(redBall)){
                    has=true;
                    break;
                }
            }
            if(has){
                str +="<font color='red'>"+ redBall + "</font> ";
            }else {
                str += redBall + " ";
            }
        }
        if(unionlotto.blueBalls!=null&&unionlotto.blueBalls.size()>0){
            str += "-";
            for(String blueBall:unionlotto.blueBalls){
                boolean has=false;
                for(String r:luckEntity.unionlotto.blueBalls){
                    if(r.equals(blueBall)){
                        has=true;
                        break;
                    }
                }
                if(has){
                    str +="<font color='red'>"+ blueBall + "</font> ";
                }else {
                    str += blueBall + " ";
                }
            }

        }else {
            if (unionlotto.blueBall.equals(luckEntity.unionlotto.blueBall)) {
                str += "- <font color='red'>" + unionlotto.blueBall + "</font> ";
            } else {
                str += "- " + unionlotto.blueBall + " ";
            }
        }
        if("未获奖".equals(unionlotto.luckResult)){
            str+=unionlotto.luckResult+"<br/>\n";
        }else{
            str+="<font color='red'>"+unionlotto.luckResult+"</font><br/>\n";
        }
        return str;
    }
    private void checkUnionlottos(final String date){
        hud.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                winningAnalyzer.analyze(new CheckCallback() {
                    @Override
                    public void callBack(Result result) {
                        if(result.ok){
                            List<Unionlotto> currentUnionlottoList=result.unionlottoWithResultList;
                            if(currentUnionlottoList.size()>0){
                                Message msg=new Message();
                                Bundle bundle=new Bundle();
                                bundle.putBoolean("ok",result.ok);
                                int i=1;
                                String str="";
                                for(Unionlotto unionlotto:currentUnionlottoList){
                                    str+=i+"、";
//                                    str+=unionlotto.description+"：";
//                                    for(String redBall:unionlotto.redBalls){
//                                        str+=redBall+" ";
//                                    }
//                                    str+="- "+unionlotto.blueBall+" "+unionlotto.luckResult+"\n";
                                    LuckEntity luckEntity=getLuckEntity(result.luckEntityList,unionlotto.getId());
                                    str+=printRight(unionlotto,luckEntity);
                                    i++;
                                }
                                bundle.putString("us",str);

                                Unionlotto right = result.right;
                                str="";
                                str+=right.date+"：";
                                for(String redBall:right.redBalls){
                                    str+=redBall+" ";
                                }
                                str+="- "+right.blueBall+"\n";
                                bundle.putString("ru",str);
                                msg.setData(bundle);
                                checkHandler.sendMessage(msg);
                            }
                        }else{
                            Message msg=new Message();
                            Bundle bundle=new Bundle();
                            bundle.putBoolean("ok",result.ok);
                            bundle.putString("msg",result.msg);
                            msg.setData(bundle);
                            checkHandler.sendMessage(msg);
                        }
                        hud.dismiss();
                    }
                },selectedDate);
            }
        }).start();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lotteryBuyDao=new LotteryBuyDao(getApplicationContext());
        lotteryBuyMultiDao=new LotteryBuyMultiDao(getApplicationContext());
        lotteryHistoryDao=new LotteryHistoryDao(getApplicationContext());
        unionlottoAnalyzer=new UnionlottoFromStoreAndNetAnalyzer(lotteryHistoryDao,
                "http://kaijiang.zhcw.com/zhcw/inc/ssq/ssq_wqhg.jsp",lotteryBuyDao,lotteryBuyMultiDao);
        winningAnalyzer=new WinningAnalyzer(lotteryHistoryDao,"http://kaijiang.zhcw.com/zhcw/inc/ssq/ssq_wqhg.jsp",lotteryBuyDao,lotteryBuyMultiDao);

        hrefTv=findViewById(R.id.hrefTv);
        String html="https://shop264863345.taobao.com";//这里即使不加协议好HTTP；也能自动被系统识别出来。
        hrefTv.setText(html);
//        hrefTv.setAutoLinkMask(Linkify.ALL);
//        hrefTv.setMovementMethod(LinkMovementMethod.getInstance());
        hrefTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openTaobaoShopping();
            }
        });

        foretellTv=findViewById(R.id.foretellTv);

        generateBt1=findViewById(R.id.generateBt1);
        generateBt2=findViewById(R.id.generateBt2);
        generateBt5=findViewById(R.id.generateBt5);
        generateBt10=findViewById(R.id.generateBt10);
        generateBt15=findViewById(R.id.generateBt15);
        generateBt20=findViewById(R.id.generateBt20);
        generateBt50=findViewById(R.id.generateBt50);
        generateBt100=findViewById(R.id.generateBt100);

        generateMultiBt1=findViewById(R.id.generateMultiBt1);
        generateMultiBt2=findViewById(R.id.generateMultiBt2);
        generateMultiBt8=findViewById(R.id.generateMultiBt8);
        generateMultiBt16=findViewById(R.id.generateMultiBt16);

        buyBt=findViewById(R.id.buyBt);
        checkBt=findViewById(R.id.checkBt);
        latestRightTv=findViewById(R.id.latestRightTv);
        luckResultTv=findViewById(R.id.luckResultTv);
        lotteryDateSp = findViewById(R.id.lotteryDateSp);
        cleanBt=findViewById(R.id.cleanBt);
        cleanBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int count=lotteryHistoryDao.clean();
                System.out.println("count->"+count);
            }
        });

        this.hud=KProgressHUD.create(this);
        this.hud.setCancellable(false);

        generateHandler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                boolean ok=msg.getData().getBoolean("ok");
                if(ok) {
                    String str = msg.getData().getString("us");
                    foretellTv.setText(str);
                    lotteryDateSp.setSelection(0);
                    latestRightTv.setText("");
                    luckResultTv.setText("");
                }else {
                    String m=msg.getData().getString("msg");
                    MyDialogUtil.showMessageDialog(MainActivity.this,"注意",m);
                }
            }
        };
        checkHandler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                boolean ok=msg.getData().getBoolean("ok");
                if(ok) {
                    String right=msg.getData().getString("ru");
                    latestRightTv.setText(right);
                    String str = msg.getData().getString("us");
                    luckResultTv.setText(Html.fromHtml(str));
                }else {
                    String m=msg.getData().getString("msg");
                    MyDialogUtil.showMessageDialog(MainActivity.this,"注意",m);
                }
            }
        };

        final String date=unionlottoAnalyzer.getCurrentDate();//获取当期日期
        System.out.println("date->"+date);
        selectedDate=date;
        List<Unionlotto> currentUnionlottoList=lotteryBuyDao.getByDate(date);
        if(currentUnionlottoList.size()==0){
            List<Unionlotto> currentUnionlottoListMulti=lotteryBuyMultiDao.getByDate(date);
            if(currentUnionlottoListMulti.size()>0){
                String str="";
                int i=1;
                for(Unionlotto unionlotto:currentUnionlottoListMulti){
                    str+=i+"、";
                    str+=unionlotto.description+": ";
                    for(String redBall:unionlotto.redBalls){
                        str+=redBall+" ";
                    }
                    str+="- ";
                    for(String blueBall:unionlotto.blueBalls){
                        str+=blueBall+" ";
                    }
                    str+="(复选)\n";
                    i++;
                }
                foretellTv.setText(str);
            }else{
                generateUnionlottos(date, 5,false);
            }
        }else{
            String str="";
            int i=1;
            for(Unionlotto unionlotto:currentUnionlottoList){
                str+=i+"、";
                str+=unionlotto.description+"：";
                for(String redBall:unionlotto.redBalls){
                    str+=redBall+" ";
                }
                str+="- "+unionlotto.blueBall+"\n";
                i++;
            }
            foretellTv.setText(str);
        }

        getAllDates();
        //将可选内容与ArrayAdapter连接起来
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,dates);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        lotteryDateSp.setAdapter(adapter);

        //添加事件Spinner事件监听
        lotteryDateSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //这里写
                selectedDate=dates.get(position);
                List<Unionlotto> currentUnionlottoList=lotteryBuyDao.getByDate(selectedDate);
                if(currentUnionlottoList.size()>0) {
                    String str = "";
                    String lstr = "";
                    int i = 1;
                    for (Unionlotto unionlotto : currentUnionlottoList) {
                        str += i + "、";
                        str += unionlotto.description + "：";
                        for (String redBall : unionlotto.redBalls) {
                            str += redBall + " ";
                        }
                        str += "- " + unionlotto.blueBall + "\n";

                        if (unionlotto.luckResult != null && !unionlotto.luckResult.trim().equals("")) {
                            lstr += i + "、";
                            lstr += unionlotto.description + "：";
                            for (String redBall : unionlotto.redBalls) {
                                lstr += redBall + " ";
                            }
                            lstr += "- " + unionlotto.blueBall;
                            if (unionlotto.luckResult.contains("等奖")) {
                                lstr += " <font color='red'>" + unionlotto.luckResult + "</font><br/>\n";
                            } else {
                                lstr += " " + unionlotto.luckResult + "<br/>\n";
                            }
                        }
                        i++;
                    }
                    foretellTv.setText(str);
                    luckResultTv.setText(Html.fromHtml(lstr));
                }else{
                    List<Unionlotto> currentUnionlottoListMulti=lotteryBuyMultiDao.getByDate(selectedDate);
                    String str = "";
                    String lstr = "";
                    int i = 1;
                    for (Unionlotto unionlotto : currentUnionlottoListMulti) {
                        str += i + "、";
                        str += unionlotto.description + "：";
                        for (String redBall : unionlotto.redBalls) {
                            str += redBall + " ";
                        }
                        str+="- ";
                        for(String blueBall:unionlotto.blueBalls){
                            str+=blueBall+" ";
                        }
                        str+="(复选)\n";

                        if (unionlotto.luckResult != null && !unionlotto.luckResult.trim().equals("")) {
                            lstr += i + "、";
                            lstr += unionlotto.description + "：";
                            for (String redBall : unionlotto.redBalls) {
                                lstr += redBall + " ";
                            }
                            lstr+="- ";
                            for(String blueBall:unionlotto.blueBalls){
                                lstr+=blueBall+" ";
                            }
                            if (unionlotto.luckResult.contains("等奖")) {
                                lstr += " <font color='red'>" + unionlotto.luckResult + "</font><br/>\n";
                            } else {
                                lstr += " " + unionlotto.luckResult + "<br/>\n";
                            }
                        }
                        i++;
                    }
                    foretellTv.setText(str);
                    luckResultTv.setText(Html.fromHtml(lstr));
                }

                Unionlotto right=lotteryHistoryDao.getByDate(selectedDate);
                if(right==null) {
                    latestRightTv.setText("");
                }else{
                    String str="";
                    str+=right.date+"：";
                    for(String redBall:right.redBalls){
                        str+=redBall+" ";
                    }
                    str+="- "+right.blueBall+"\n";
                    latestRightTv.setText(str);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //设置默认值
        lotteryDateSp.setVisibility(View.VISIBLE);

        class GBListener implements View.OnClickListener{
            private int count=0;
            private boolean multi=false;
            public GBListener(int count,boolean multi) {
                this.count = count;
                this.multi=multi;
            }

            @Override
            public void onClick(View view) {
                //生成
                List<Unionlotto> currentUnionlottoList=lotteryBuyDao.getByDate(date);
                if(currentUnionlottoList.size()>0){
                    Unionlotto unionlotto=currentUnionlottoList.get(0);
                    if(unionlotto.bought==1){//已经购买不能在生成
                        //弹窗说明
                        MyDialogUtil.showMessageDialog(MainActivity.this,"注意","已经买定,不能重新生成！");
                        return;
                    }
                }else{
                    List<Unionlotto> currentUnionlottoListMulti=lotteryBuyMultiDao.getByDate(date);
                    if(currentUnionlottoListMulti.size()>0){
                        Unionlotto unionlotto=currentUnionlottoListMulti.get(0);
                        if(unionlotto.bought==1){//已经购买不能在生成
                            //弹窗说明
                            MyDialogUtil.showMessageDialog(MainActivity.this,"注意","已经买定,不能重新生成！");
                            return;
                        }
                    }
                }
                generateUnionlottos(date,this.count,this.multi);
            }
        };
        generateBt1.setOnClickListener(new GBListener(1,false));
        generateBt2.setOnClickListener(new GBListener(2,false));
        generateBt5.setOnClickListener(new GBListener(5,false));
        generateBt10.setOnClickListener(new GBListener(10,false));
        generateBt15.setOnClickListener(new GBListener(15,false));
        generateBt20.setOnClickListener(new GBListener(20,false));
        generateBt50.setOnClickListener(new GBListener(50,false));
        generateBt100.setOnClickListener(new GBListener(100,false));

        generateMultiBt1.setOnClickListener(new GBListener(1,true));
        generateMultiBt2.setOnClickListener(new GBListener(2,true));
        generateMultiBt8.setOnClickListener(new GBListener(8,true));
        generateMultiBt16.setOnClickListener(new GBListener(16,true));

        buyBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Unionlotto> currentUnionlottoList=lotteryBuyDao.getByDate(date);
                if(currentUnionlottoList.size()>0){
                    Unionlotto unionlotto=currentUnionlottoList.get(0);
                    if(unionlotto.bought==1){//已经购买不能在生成
                        //弹窗说明
                        MyDialogUtil.showMessageDialog(MainActivity.this,"注意","已经买定,无需重新买定！");
                        return;
                    }
                }else{
                    List<Unionlotto> currentUnionlottoListMulti=lotteryBuyMultiDao.getByDate(date);
                    if(currentUnionlottoListMulti.size()>0){
                        Unionlotto unionlotto=currentUnionlottoListMulti.get(0);
                        if(unionlotto.bought==1){//已经购买不能在生成
                            //弹窗说明
                            MyDialogUtil.showMessageDialog(MainActivity.this,"注意","已经买定,无需重新买定！");
                            return;
                        }
                    }
                }
                MyDialogUtil.showBuyConfirm(MainActivity.this, new CommonDialog.CommonDialogListener() {
                    @Override
                    public void onBtn1Click() {

                    }

                    @Override
                    public void onBtn2Click() {
                        lotteryBuyDao.updateUnionlottoToBought(date);
                        lotteryBuyMultiDao.updateUnionlottoToBought(date);
                    }
                });
            }
        });
        checkBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkUnionlottos(selectedDate);
            }
        });
        statisticBt=findViewById(R.id.statisticBt);
        statisticBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,StatisticActivity.class);
                startActivity(intent);
            }
        });
        exportBt=findViewById(R.id.exportBt);
        importBt=findViewById(R.id.importBt);
        exportBt.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                requestPermission(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE, new RequestPermissionsBack() {
                    @Override
                    public void onAgree() {
                        String path= Environment.getExternalStorageDirectory().getAbsolutePath();
                        path+="/unionlotto_bought.txt";
                        BufferedWriter bw =null;
                        int count=0;
                        String errMsg="";
                        try {
                            System.out.println(path);
                            FileOutputStream fos=new FileOutputStream(path);
                            bw = new BufferedWriter(new OutputStreamWriter(fos));
                            List<Unionlotto> all = lotteryBuyDao.getAll();
                            for(Unionlotto unionlotto:all){
                                String line=unionlotto.getId()+","+unionlotto.date+","+unionlotto.description;
                                int i=1;
                                for(String redBall:unionlotto.getRedBalls()){
                                    line+=","+redBall;
                                    i++;
                                }
                                line+=","+unionlotto.blueBall;
                                line+=","+unionlotto.bought;
                                line += "," + unionlotto.luckResult;
                                bw.write(line);
                                bw.newLine();
                                count++;
                            }
                            List<Unionlotto> allMulti = lotteryBuyMultiDao.getAll();
                            for(Unionlotto unionlotto:allMulti){
                                String line=unionlotto.getId()+"-"+unionlotto.date+"-"+unionlotto.description+"-";
                                int i=0;
                                for(String redBall:unionlotto.getRedBalls()){
                                    if(i==0){
                                        line += redBall;
                                    }else {
                                        line += "," + redBall;
                                    }
                                    i++;
                                }
                                line+="-";
                                i=0;
                                for(String blueBall:unionlotto.blueBalls){
                                    if(i==0){
                                        line += blueBall;
                                    }else {
                                        line += "," + blueBall;
                                    }
                                }
                                line+="-"+unionlotto.bought;
                                line += "-" + unionlotto.luckResult;
                                bw.write(line);
                                bw.newLine();
                                count++;
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            errMsg=e.getMessage();
                        }finally {
                            if(bw!=null){
                                try {
                                    bw.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        System.out.println("导出["+count+"]行数据到文件["+path+"]");
                        Toast.makeText(getApplicationContext(), "导出["+count+"]行数据到文件["+path+"]", Toast.LENGTH_LONG).show();
                        if(!errMsg.equals("")){
                            System.out.println("导出出错："+errMsg);
                            Toast.makeText(getApplicationContext(), "导出出错："+errMsg, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onDisagree() {
                        Toast.makeText(getApplicationContext(), "请打开存储权限", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        importBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE, new RequestPermissionsBack() {
                    @Override
                    public void onAgree() {
                        String path= Environment.getExternalStorageDirectory().getAbsolutePath();
                        new LFilePicker()
                                .withActivity(MainActivity.this)
                                .withRequestCode(REQUESTCODE_FROM_ACTIVITY_CHOOSE_FILE)
                                .withChooseMode(true)
                                .withStartPath(path)//指定初始显示路径
                                .withIsGreater(false)//过滤文件大小 小于指定大小的文件
                                .withFileSize(50 * 1024 * 1024)//指定文件大小为50M
                                .start();
                    }

                    @Override
                    public void onDisagree() {
                        Toast.makeText(getApplicationContext(), "请打开存储权限", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }
    private void getAllDates(){
        String date=unionlottoAnalyzer.getCurrentDate();//获取当期日期
        dates=lotteryBuyDao.getDates();
        List<String> dates1 = lotteryBuyMultiDao.getDates();
        for(String s:dates1){
            boolean in=false;
            for(String m:dates){
                if(m.equals(s)){
                    in=true;
                    break;
                }
            }
            if(!in){
                dates.add(s);
            }
        }
        if(dates.size()==0){
            dates.add(date);
        }
        Collections.sort(dates, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2)*(-1);
            }
        });
        if(!date.equals(dates.get(0))){
            dates.add(0,date);
        }
    }
    private int REQUESTCODE_FROM_ACTIVITY_CHOOSE_DIR = 1000;
    private int REQUESTCODE_FROM_ACTIVITY_CHOOSE_FILE = 1001;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUESTCODE_FROM_ACTIVITY_CHOOSE_DIR) {//导出数据,暂时不用
                //如果是文件夹选择模式，需要获取选择的文件夹路径
                //String path = data.getStringExtra("path");
                //Toast.makeText(getApplicationContext(), "选中的路径为" + path, Toast.LENGTH_SHORT).show();
            }else if(requestCode == REQUESTCODE_FROM_ACTIVITY_CHOOSE_FILE){//导入数据
                //如果是文件选择模式，需要获取选择的所有文件的路径集合
                //List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);//Constant.RESULT_INFO == "paths"
                List<String> list = data.getStringArrayListExtra("paths");
                //Toast.makeText(getApplicationContext(), "选中了" + list.size() + "个文件", Toast.LENGTH_SHORT).show();
                System.out.println(list);
                for(String path:list){
                    int count=0;
                    BufferedReader br =null;
                    try {
                        System.out.println(path);
                        FileInputStream fis=new FileInputStream(path);
                        br = new BufferedReader(new InputStreamReader(fis));
                        String line=null;
                        while ((line=br.readLine())!=null){
                            String[] ss=line.split("\\-");
                            if(ss.length==7){//复选的
                                Unionlotto unionlotto = new Unionlotto();
                                if (!isNumber(ss[0])) {
                                    continue;
                                }
                                unionlotto.setId(Integer.parseInt(ss[0]));
                                unionlotto.setDate(ss[1]);
                                unionlotto.setDescription(ss[2]);
                                List<String> redBalls = new ArrayList<>();
                                String redBallsStr=ss[3];
                                String []redBallsStrs=redBallsStr.split(",");
                                for (int i = 0; i < redBallsStrs.length; i++) {
                                    if (isNumber(redBallsStrs[i])) {
                                        redBalls.add(redBallsStrs[i]);
                                    }
                                }
                                unionlotto.redBalls=redBalls;
                                List<String> blueBalls = new ArrayList<>();
                                String blueBallsStr=ss[4];
                                String []blueBallsStrs=blueBallsStr.split(",");
                                for (int i = 0; i < blueBallsStrs.length; i++) {
                                    if (isNumber(blueBallsStrs[i])) {
                                        blueBalls.add(blueBallsStrs[i]);
                                    }
                                }
                                unionlotto.blueBalls=blueBalls;
                                unionlotto.setBought(Integer.parseInt(ss[5]));
                                if (!"null".equals(ss[6])) {
                                    unionlotto.setLuckResult(ss[6]);
                                }
                                //导入一行数据
                                int r = lotteryBuyMultiDao.importRow(unionlotto);
                                if (r > 0) {
                                    count++;
                                }
                            }else {
                                String[] split = line.split(",");
                                if (split.length == 12) {
                                    Unionlotto unionlotto = new Unionlotto();
                                    if (!isNumber(split[0])) {
                                        continue;
                                    }
                                    unionlotto.setId(Integer.parseInt(split[0]));
                                    unionlotto.setDate(split[1]);
                                    unionlotto.setDescription(split[2]);
                                    List<String> redBalls = new ArrayList<>();
                                    boolean err = false;
                                    for (int i = 3; i < 3 + 6; i++) {
                                        if (!isNumber(split[i])) {
                                            err = true;
                                            break;
                                        }
                                        redBalls.add(split[i]);
                                    }
                                    if (err) {
                                        continue;
                                    }
                                    unionlotto.setRedBalls(redBalls);
                                    if (!isNumber(split[9])) {
                                        continue;
                                    }
                                    unionlotto.setBlueBall(split[9]);
                                    if (!isNumber(split[10])) {
                                        continue;
                                    }
                                    unionlotto.setBought(Integer.parseInt(split[10]));
                                    if (!"null".equals(split[11])) {
                                        unionlotto.setLuckResult(split[11]);
                                    }
                                    //导入一行数据
                                    int r = lotteryBuyDao.importRow(unionlotto);
                                    if (r > 0) {
                                        count++;
                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        if(br!=null){
                            try {
                                br.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    System.out.println("从文件["+path+"]导入["+count+"]行数据");
                    Toast.makeText(getApplicationContext(), "从文件["+path+"]导入["+count+"]行数据", Toast.LENGTH_LONG).show();
//                    getAllDates();
////                    adapter.notifyDataSetChanged();
                    recreate();
                }
            }
        }
    }
    private boolean isNumber(String str){
        try {
            Integer.parseInt(str);
        }catch (Exception ex){
            return false;
        }
        return true;
    }



    //权限code定义
    public static final int REQUEST_CODE_PERMISSION = 0x1111;
    public final static int REQUEST_CODE_WRITE_EXTERNAL_STORAGE=0x1234;
    public static interface RequestPermissionsBack{
        void onAgree();
        void onDisagree();
    }
    private RequestPermissionsBack requestPermissionsBack;
    public void requestPermission(Activity context, String[] permissions, int requestCode, RequestPermissionsBack requestPermissionsBack) {
        this.requestPermissionsBack=requestPermissionsBack;
        boolean got=true;
        for(String permission:permissions){
            if(ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED){
                got=false;
                break;
            }
        }
        if (!got) {
            // Do not have the permission of camera, request it.
            ActivityCompat.requestPermissions(context, permissions, requestCode);
        } else {
            // Have gotten the permission
            requestPermissionsBack.onAgree();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // User agree the permission
                    requestPermissionsBack.onAgree();
                } else {
                    // User disagree the permission
                    requestPermissionsBack.onDisagree();
                }
            }
            break;
            case REQUEST_CODE_WRITE_EXTERNAL_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // User agree the permission
                    requestPermissionsBack.onAgree();
                } else {
                    // User disagree the permission
                    requestPermissionsBack.onDisagree();
                }
            }
            break;
        }
    }


    private boolean checkPackage(String packageName) {
        if (packageName == null || "".equals(packageName)) return false;
        try {
            getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    private void openTaobaoShopping() {
        if (checkPackage("com.taobao.taobao")) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
//            https://detail.tmall.com/item.htm?id=535823983028&spm=a21bo.7932663.item.2.0mvUrk&scm=1007.13596.65361.100200300000014
            String url = "taobao://shop264863345.taobao.com";
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            startActivity(intent);
        } else {
            Uri uri = Uri.parse("https://shop264863345.taobao.com");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }
}
